﻿using AutoMapper;
using Harmontronics.IService;
using Harmontronics.Model.Dto.Login;
using Harmontronics.Model.Dto.User;
using Harmontronics.Model.Entitys;
using Harmontronics.Model.Other;
using Harmontronics.Repository;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Harmontronics.Service
{
    public class UserService : IUserService
    {
        private readonly IMapper _mapper;
        private HcDbContext _db { get; set; }

        public UserService(IMapper mapper, HcDbContext db)
        {
            _mapper = mapper;
            _db = db;
        }

        public UserRes GetUser(string EmployeeNumber, string password)
        {
            List<Users> users = _db.Users.ToList();
            Users user = _db.Users?.Where(u => u.EmployeeNumber == EmployeeNumber && u.Password == password).FirstOrDefault();
            if (user != null)
            {
                return _mapper.Map<UserRes>(user);
            }
            return new UserRes();
        }

        public List<UserReq> GetUsersList()
        {
            List<Users> usersList = _db.Users!.ToList();
            List<UserReq> userReqs = new List<UserReq>();
            foreach (var user in usersList)
            {
                userReqs.Add(_mapper.Map<UserReq>(user));
            }
            return userReqs;
        }


        public bool AddUser(UserAdd input)
        {
            var user = _mapper.Map<Users>(input);
            user.CreateTime = DateTime.Now;
            try
            {
                _db.Users?.Add(user);
                _db.SaveChanges();
                //修改权限_用户表
                Users newUser = _db.Users.SingleOrDefault(i => i.EmployeeNumber == input.EmployeeNumber);
                if (newUser != null)
                {
                    ChangeUserRoleRelation(newUser.Id, (int)input.RoleIds);
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
        private bool ChangeUserRoleRelation(int userId, int roleId)
        {
            _db.UserRoleRelation.Add(new UserRoleRelation
            {
                UserId = userId,
                RoleId = roleId
            });

            _db.SaveChanges();
            return true;
        }
        public bool Update(UserEdit input)
        {
            try
            {
                Users user = _db.Users?.Where(u => u.Id == input.Id).FirstOrDefault();
                if (user != null)
                {
                    int oldEnable = user.Enable;
                    int oldDel = user.IsDeleted;
                    _mapper.Map(input, user);
                    user.Enable = oldEnable;
                    user.IsDeleted = oldDel;
                    user.UpdateTime = DateTime.Now;
                    _db.Users?.Update(user);
                    _db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }

        public bool DeleteUser(int id)
        {
            try
            {
                Users user = _db.Users.Where(i => i.Id == id).FirstOrDefault();
                List<UserRoleRelation> relations = _db.UserRoleRelation.Where(i => i.UserId == id).ToList();
                if (user != null)
                {
                    _db.Users?.Remove(user);
                    _db.UserRoleRelation.RemoveRange(relations);
                    _db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
        //批量删除
        public bool BatchDel(List<int> ids)
        {
            try
            {
                List<Users> entities = _db.Users.Where(i => ids.Contains(i.Id)).ToList();
                List<UserRoleRelation> relations = _db.UserRoleRelation.Where(i => ids.Contains(i.UserId)).ToList();
                if (entities.Count > 0)
                {
                    _db.Users.RemoveRange(entities);
                    _db.UserRoleRelation.RemoveRange(relations);
                }
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }


        public UserReq GetUserReqById(int id)
        {
            var user = _db.Users!.SingleOrDefault(u => u.Id == id);
            if (user != null)
            {
                return _mapper.Map<UserReq>(user);
            }
            return new UserReq();
        }

        public UserReq GetUsersByEmp(string emp)
        {
            var user = _db.Users!.SingleOrDefault(u => u.EmployeeNumber == emp);
            if (user != null)
            {
                return _mapper.Map<UserReq>(user);
            }
            return new UserReq();
        }

        public bool ResetPwdOrStatus(ResetPwdInput input)
        {
            try
            {
                Users user = _db.Users.SingleOrDefault(i => i.Id == input.id);
                if (user != null)
                {
                    if (input.enable == 0 || input.enable == 1)
                    {
                        user.Enable = input.enable;
                    }
                    if (!input.password.IsNullOrEmpty())
                    {
                        user.Password = input.password;
                    }
                }
                _db.SaveChanges();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;

        }

        public bool DeleteHeadPortrait(string employeeNumber)
        {
            Users user = _db.Users.SingleOrDefault(i => i.EmployeeNumber == employeeNumber);
            if (user != null && user.HeadPortrait != null)
            {
                try
                {
                    //删除文件
                    File.Delete(user.HeadPortrait);
                    //置空url
                    user.HeadPortrait = null;
                    _db.Update(user);
                    _db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return false;
                }
            }

            return true;
        }

        public ApiResponseData SaveHeadPortrait(FileupLoadInput input)
        {
            Users user = _db.Users.SingleOrDefault(i => i.EmployeeNumber == input.employeeNumber);
            if (user == null)
            {
                return new ApiResponseData() { code = 500, message = "The user does not exist!" };
            }
            IFormFile file = input.file;
            if (file == null || file.Length <= 0)
            {
                return new ApiResponseData() { code = 500, message = "No image data was received" };
            }

            // 获取文件名及其后缀
            var fileName = Path.GetFileNameWithoutExtension(file.FileName);
            var extension = Path.GetExtension(file.FileName).ToLower();

            // 验证文件格式（这里只接受 jpg、png 等常见图像格式）
            if (!extension.Equals(".jpg") && !extension.Equals(".jpeg") && !extension.Equals(".png"))
            {
                return new ApiResponseData() { code = 500, message = "$Invalid image format '{extension}'" };
            }
            string headPicName = DateTime.Now.ToString("yyyyMMddHHmmss") + RandomString.GetRandomString(5);
            string picPath = $"Resources/Picture/headPortrait/" + headPicName + extension;
            try
            {
                using (FileStream img = new FileStream(picPath, FileMode.OpenOrCreate))
                {
                    file.CopyTo(img);
                    img.Close();
                }
                user.HeadPortrait = picPath;
                _db.Update(user);
                _db.SaveChanges();
                return new ApiResponseData()
                {
                    code = 200,
                    data = new
                    {
                        path = picPath,
                    },
                    message = "success!"
                };
            }
            catch (Exception ex)
            {
                return new ApiResponseData() { code = 500, message = "Image saving failure!" };
            }
        }

        public Users GetUsersById(int id)
        {
            try
            {
                return _db.Users.SingleOrDefault(i => i.Id == id);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
